/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Windows.Input;
using System.Windows.Controls;
using System.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for MessageBox.xaml
    /// </summary>
    public partial class InclusiveTaxSelectionListBox : ModalWindow
    {
        private int listScrollIndex = 0;

        static UserResponse lastResponse = UserResponse.EXIT;
        public static UserResponse LastResponse
        {
            get { return lastResponse; }
            set { lastResponse = value; }
        }


        public static string ChosenString
        {
            get;
            set;
        }

        public static Int64 ChosenId
        {
            get;
            set;
        }

        private List<INCLUSIVE_TAXRATE> choicesList = null;
        DominicaEntities context;
        /// <summary>
        /// 
        /// </summary>
        /// <param Name="closedCallback"></param>
        public InclusiveTaxSelectionListBox(DominicaEntities context)
            : base()
        {
            PosWindow.MainPosWindow.Topmost = false;
            InitializeComponent();
            this.context = context;
            textBlockMessage.Text = "Select an inclusive tax rate from the list, or create a new inclusive tax rate.  Inclusive tax rates are built-in to the price of the product itself and are often used in conjunction with alcohol sales.  This rate will not change the product's price, but will be used in reporting to calculate your net sales.";

            buttonClose.MouseDown += new MouseButtonEventHandler(buttonClose_MouseDown_NOTHROW);
            buttonOk.MouseDown += new MouseButtonEventHandler(buttonOk_MouseDown_NOTHROW);
            buttonLeftArrow.MouseDown += new MouseButtonEventHandler(buttonLeftArrow_MouseDown_NOTHROW);
            buttonRightArrow.MouseDown += new MouseButtonEventHandler(buttonRightArrow_MouseDown_NOTHROW);

            this.Closing += new System.ComponentModel.CancelEventHandler(MessageBox_Closing_NOTHROW);
            this.buttonEdit.MouseDown += new MouseButtonEventHandler(buttonEdit_MouseDown);
        }

        void buttonEdit_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (choicesList.Count != 0)
                {
                    Oceanside.FullKeyboard.ActiveKeyboard.SetSmallMode();
                    INCLUSIVE_TAXRATE iRate = null;
                    if (choicesList != null && choicesList.Count != 0)
                    {
                        iRate = choicesList[listScrollIndex];
                    }

                    Oceanside.FullKeyboard.ChildWindow = this;
                    Oceanside.FullKeyboard.ActiveKeyboard.ShowMe(
                        new List<Control> { textBlockCompName, tbFlatRate });

                    if (Oceanside.FullKeyboard.LastResponse != UserResponse.EXIT)
                    {
                        string rate = tbFlatRate.Text;

                        if (!String.IsNullOrEmpty(textBlockCompName.Text) && !String.IsNullOrEmpty(rate))
                        {
                            decimal dRate;
                            if (Decimal.TryParse(rate, out dRate))
                            {
                                INCLUSIVE_TAXRATE tr = choicesList[listScrollIndex];
                                tr.Name = textBlockCompName.Text;
                                tr.Rate = dRate;
                                context.SaveChanges();
                            }
                            else
                            {
                                UMD.ShowGuiMessageSTASafe_NOTHROW("The value that you entered for the tax rate was invalid.  Please enter a value such as 8.25 for 8.25%.");
                            }
                        }
                        else
                        {
                            UMD.ShowGuiMessageSTASafe_NOTHROW("Please provide values for all of the fields.");
                        }
                    }
                }
                else
                {
                    imageKeyboard_MouseDown(null, null);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool InitChoices()
        {
            bool wasSuccess = false;
            try
            {
                var q = from tr in context.INCLUSIVE_TAXRATES where tr.IsDeleted == false select tr;
                if (q.Any())
                {
                    choicesList = q.ToList();
                }
                wasSuccess = true;
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            this.DataContext = null;
            if (choicesList != null && listScrollIndex < choicesList.Count && listScrollIndex >= 0)
            {
                this.DataContext = choicesList[listScrollIndex];
            }
            return wasSuccess;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imageKeyboard_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                Oceanside.FullKeyboard.ActiveKeyboard.SetSmallMode();
                INCLUSIVE_TAXRATE iRate = null;
                if (choicesList != null && choicesList.Count != 0)
                {
                    iRate = choicesList[listScrollIndex];
                }

                Oceanside.FullKeyboard.ChildWindow = this;
                Oceanside.FullKeyboard.ActiveKeyboard.ShowMe(
                    new List<Control> { textBlockCompName, tbFlatRate });

                if (Oceanside.FullKeyboard.LastResponse != UserResponse.EXIT)
                {
                    string rate = tbFlatRate.Text;

                    if (!String.IsNullOrEmpty(textBlockCompName.Text) && !String.IsNullOrEmpty(rate))
                    {
                        decimal dRate;
                        if (Decimal.TryParse(rate, out dRate))
                        {
                            INCLUSIVE_TAXRATE tr = new INCLUSIVE_TAXRATE();
                            tr.Name = textBlockCompName.Text;
                            tr.Rate = dRate;
                            context.INCLUSIVE_TAXRATES.AddObject(tr);
                            context.SaveChanges();
                            InitChoices();
                            listScrollIndex = choicesList.Count - 1;
                        }
                        else
                        {
                            UMD.ShowGuiMessageSTASafe_NOTHROW("The value that you entered for the tax rate was invalid.  Please enter a value such as 8.25 for 8.25%.");
                        }
                    }
                    else
                    {
                        UMD.ShowGuiMessageSTASafe_NOTHROW("Please provide values for all of the fields.");
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MessageBox_Closing_NOTHROW(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                ModalDialogIsOpen = false;
                CurrentlyOpenInstance = null;
#if !_DEBUG
                PosWindow.MainPosWindow.Topmost = true;
#endif
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SLIST_CLOSING, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void buttonRightArrow_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;

                if (choicesList != null)
                {
                    if (listScrollIndex < choicesList.Count - 1)
                    {
                        listScrollIndex++;
                    }
                    else
                    {
                        listScrollIndex = 0;
                    }
                    if (choicesList.Count != 0)
                    {
                        this.DataContext = choicesList[listScrollIndex];
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SLIST_ARRW_RIGHT_MOUSE_DWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void buttonLeftArrow_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                if (choicesList != null)
                {
                    if (listScrollIndex > 0)
                    {
                        listScrollIndex--;
                    }
                    else if (choicesList.Count == 0)
                    {
                        listScrollIndex = 0;
                    }
                    else
                    {
                        listScrollIndex = choicesList.Count - 1;
                    }
                    if (choicesList.Count != 0)
                    {
                        this.DataContext = choicesList[listScrollIndex];
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SLIST_ARRW_LEFT_MOUSE_DWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void buttonOk_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                LastResponse = UserResponse.ENTER;

                if (choicesList != null && choicesList.Count != 0)
                {
                    ChosenId = choicesList[listScrollIndex].Id;
                }
                this.Close();
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SLIST_OK_MOUSEDOWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void buttonClose_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                LastResponse = UserResponse.EXIT;
                this.Close();
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SLIST_CLOSE_MOUSEDOWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteRevenueTypeButton_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (choicesList != null && choicesList.Count != 0)
                {
                    Int64 id = choicesList[listScrollIndex].Id;
                    var q = from TR in context.INCLUSIVE_TAXRATES where TR.Id == id select TR;
                    if (q.Any())
                    {
                        INCLUSIVE_TAXRATE tr = q.First();
                        tr.IsDeleted = true;
                        context.SaveChanges();
                        choicesList.RemoveAt(listScrollIndex);
                        listScrollIndex = 0;
                        InitChoices();
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }
    }
}
